<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/11/20
 * Time: 9:12
 */

namespace app\index\controller;


use Redis\Redis;
use think\Controller;
use think\Db;

class TimeTask extends Controller
{

    static function payRedis($bizId)
    {
        if (!empty($bizId)) {
            $redis = new Redis();
            $payRedisInfo = $redis->hGet('payRedis' . $bizId);
            if (!empty($payRedisInfo)) {
                /*array(1) {
  ["abc"] => string(43) "{"pay_type":1,"time":"2021-09-02 07:42:14"}"
}*/
                $ordersPay = new OrdersPay();
                foreach ($payRedisInfo as $k => $v) {
                    $payInfo = json_decode($v, true);
                    # 判断时间
                    if ($payInfo['time'] < date('Y-m-d H:i:s', strtotime('- 3 minutes'))) {
                        # 查询订单的支付状态
                        $orderRes = $ordersPay->OrderStatusQuery($k, $payInfo['payType'], $payInfo['payPrice']);
                        # 清除缓存
                        $redis->hDel('payRedis' . $bizId, $k);
                        # 数据库记录一下
                        Db::table('aaa')->insert(array('info' => json_encode($orderRes) . '=>' . $v, 'type' => 'payRedis' . $bizId));
                    }
                }
            }
        }
    }

    /**
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * @content 员工自动转正
     */
    static function autoFormal()
    {
        $redis = new Redis();
        $status = $redis->get('autoFormal');
        if (!empty($status)) {
            return false;
        }
        $redis->set('autoFormal', 'YES');
        changeEmployeeStatus();
        Db::table('employee e')
            ->where("e.employee_status = 1 and ((select employee_positive from employee_mapping where employee_id = e.id) <= '" . date('Y-m-d') . "') ")
            ->update(array('employee_status' => 2));
        $redis->delete('autoFormal');
    }

    /**
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @content 24小时未评论自动结算
     */
    static function settlementTask($bizId)
    {
        $redis = new Redis();
        /* $status = $redis->get('settlementTask'.$bizId);
         if (!empty($status)) {
             return false;
         }
         $redis->set('settlementTask'.$bizId, 'YES');*/
        $status = $redis->lock('settlementTask' . $bizId);
        if ($status) {
            $time = date('Y-m-d H:i:s', strtotime('-1 day'));
            if ($bizId == 692) {
                #诚信店
                $time = date('Y-m-d 23:59:59', strtotime('-1 day'));
            }
//            $time = date('Y-m-d H:i:S');
            # 查询超过24小时未评论的未处理的未结算数据
            $info = Db::table('biz_settlement bs')
                ->field('bs.id,bs.price,bs.biz_id,commission_price,tobe_settled,bs.order_number,o.is_online')
                ->join('orders o', 'o.order_number = bs.order_number', 'left')
                ->where(array('bs.settlement_status' => '1', 'bs.desposit_status' => '1', 'o.evaluation_status' => '1', 'bs.type' => '1', 'bs.mark' => '1'))
                ->where("o.order_over <= '" . $time . "'")
                ->order('bs.id asc')
                ->select();
            if (!empty($info)) {
                foreach ($info as $k => $v) {
                    # 查询门店抵押金 , 门店历史结算金额
                    $bizInfo = Db::table('biz')->field('settlement_count,security_price,account_balance')->where(array('id' => $v['biz_id']))->find();
                    # 结算信息
                    $settlementInfo = TimeTask::settlementPriceInfo($v['order_number'], $v['biz_id'], $v['is_online']);
                    # 结算金额
                    $price = $settlementInfo['price'];
                    # 抽成金额
                    $commission_price = $settlementInfo['commission_price'];
                    $tobe_settled = $price + $commission_price;
                    if ($bizInfo['security_price'] == 0) {
                        # 加门店余额
                        Db::table('biz')->where(array('id' => $v['biz_id']))->setInc('account_balance', $price);
                        # 结算改为已处理
                        Db::table('biz_settlement')->where(array('id' => $v['id']))->update(array(
                            'desposit_status' => 2, 'settlement_status' => 2, 'price' => $price, 'commission_price' => $commission_price));
                        # 修改合作店抽成(biz_income)
                        Db::table('biz_income')->where(array('pid' => $v['order_number']))->update(array('biz_income' => $commission_price));
                    } else {
                        # 加上本次结算金额后与抵押金作比较
                        $settlement_count = $bizInfo['settlement_count'] + $price;
                        if ($settlement_count <= $bizInfo['security_price']) {
                            Db::table('biz')->where(array('id' => $v['biz_id']))->setInc('settlement_count', $price);
                            # 结算改为已处理
                            Db::table('biz_settlement')->where(array('id' => $v['id']))->update(array(
                                'desposit_status' => 2, 'price' => $price, 'commission_price' => $commission_price));
                        } else {
                            # 大于抵押金,将超过抵押金的部分进行结算()
                            $exceed = $settlement_count - $bizInfo['security_price'];
                            if ($exceed != $price) {
                                # 修改结算金额
                                Db::table('biz_settlement')->where(array('id' => $v['id']))->update(array('price' => $exceed));
                            }
                            # 加门店余额
                            Db::table('biz')->where(array('id' => $v['biz_id']))->setInc('account_balance', $exceed);
                            Db::table('biz')->where(array('id' => $v['biz_id']))->update(array('settlement_count' => $bizInfo['security_price']));
                            # 结算改为已处理
                            Db::table('biz_settlement')->where(array('id' => $v['id']))->update(array(
                                'desposit_status' => 2, 'settlement_status' => 2, 'price' => $price, 'commission_price' => $commission_price));
                            # 修改合作店抽成(biz_income)
                            Db::table('biz_income')->where(array('pid' => $v['order_number']))->update(array('biz_income' => $commission_price));
                        }
                    }
                    # 应结算金额
                    Db::table('biz_settlement')->where(array('id' => $v['id']))->update(array('tobe_settled' => $tobe_settled));
                    # 完成任务
                    BizTask::FinishTask(2, $v['biz_id'], $price);
                }
            }
            # 办理会员/充值/升级   24小时后自动进入余额
            $balance = Db::table('biz_settlement')
                ->field('id,price,biz_id')
                ->where(array('settlement_status' => 1, 'desposit_status' => 1, 'mark' => 1))
                ->where("create_time <= '" . date('Y-m-d H:i:s', strtotime('-1 day')) . "'")
                ->where("type != 1")
                ->select();
            if (!empty($balance)) {
                foreach ($balance as $k => $v) {
                    # 加余额
                    Db::table('biz')->where(array('id' => $v['biz_id']))->setInc('account_balance', $v['price']);
                    # 改状态
                    Db::table('biz_settlement')->where(array('id' => $v['id']))->update(array(
                        'desposit_status' => 2, 'settlement_status' => 2));
                }
            }
//            $redis->delete('settlementTask' . $bizId);
            $redis->unlock('settlementTask' . $bizId);
        }
    }

    /**
     * @param $orderNumber
     * @param $bizId
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @content  计算该订单的结算金额
     */
    static function settlementPriceInfo($orderNumber, $bizId, $is_online)
    {
        # 门店信息
//        $bizCommissionInfo = Db::table('biz')
//            ->where(array('id' => $bizId))
//            ->find();
        # 查询订单详情
        # 商品工单
        $orderBiz = Db::table('order_biz ob')
            ->field('ob.id,ob.pro_price,ob.original_pro_price original_price,price_settlement,final_settlement,2 type,custommark,
            (select score from evaluation_score where orderserver_id = ob.id and type=2 limit 1) score,settlement_type,2 relation_eva')
            ->where(array('order_number' => $orderNumber))
            ->buildSql();
        # 查询该订单下的服务工单
        $temporary = Db::table('order_server os')
            ->field('os.id,os.price,os.original_price,price_settlement,final_settlement,1 type,custommark,
            (select score from evaluation_score where orderserver_id = os.id and type=1 limit 1) score,settlement_type,
            if(custommark=1,(select relation_eva from service where id =os.server_id),2) relation_eva')
            ->where(array('order_number' => $orderNumber))
            ->union([$orderBiz])
            ->buildSql();
        # 联合查询
        $orderDetail = Db::table($temporary . 't')->select();
        $price = 0;
        $withdrawal_amount = 0;
        $withdrawal_amount_count = 0;
        # 线上订单抽成 5% 门店订单抽成 10% (门店洗车场(id: 692) 不抽成)
        if ($is_online == 1) {
            # 线上订单
            $drawRatio = 0;
        } else {
            # 门店订单
            $drawRatio = 0.1;
        }
        if ($bizId == 692) {
            $drawRatio = 0;
        }
        foreach ($orderDetail as $k => $v) {
            $settlement_ratio = config('ecarcoo.comment_rate_settlement')['medium'];
            if ($v['settlement_type'] == 2) {
                # 活动结算金额  不走评论
                $settlement_ratio = 1;
            }
            if ($v['type'] == 1) {
                # 服务工单
                # 计算抽成
                if ($v['custommark'] == 1) {
                    # 系统服务
//                    $withdrawal_amount = $v['price_settlement'] * $bizCommissionInfo['extract_platservice'];
                    $withdrawal_amount = $v['price_settlement'] * $drawRatio;
//                    if ($v['relation_eva'] == 1) {
//                        # 关联评价
//                        $withdrawal_amount_count += $v['price_settlement'] * $bizCommissionInfo['extract_platservice'] * $settlement_ratio;
//                    } else {
//                        # 不关联评价
//                        $withdrawal_amount_count += $v['price_settlement'] * $bizCommissionInfo['extract_platservice'];
//                    }
                    if (false) {//$bizCommissionInfo['relevant_evaluation'] == 1
                        # 门店设置里面关联评价
//                        $withdrawal_amount_count += $v['price_settlement'] * $bizCommissionInfo['extract_platservice'] * $settlement_ratio;
                        $withdrawal_amount_count += $v['price_settlement'] * $drawRatio * $settlement_ratio;
                    } else {
                        # 门店设置  不 关联评价
//                        $withdrawal_amount_count += $v['price_settlement'] * $bizCommissionInfo['extract_platservice'];
                        $withdrawal_amount_count += $v['price_settlement'] * $drawRatio;
                    }
                } else {
                    # 自定义服务
//                    $withdrawal_amount = $v['price_settlement'] * $bizCommissionInfo['extract_selfservice'];
                    $withdrawal_amount = $v['price_settlement'] * $drawRatio;
//                    $withdrawal_amount_count += $v['price_settlement'] * $bizCommissionInfo['extract_selfservice'];
                    $withdrawal_amount_count += $v['price_settlement'] * $drawRatio;
                }
                $settlement_order = $v['price_settlement'] - $withdrawal_amount;
                # 结算金额
                if ($v['custommark'] == 1) {
                    # 系统服务,最终结算价格
//                    if ($v['relation_eva'] == 1) {
//                        # 该服务 关联用户评价
//                        $final_settlement = $settlement_order * $settlement_ratio;
//                    } else {
//                        # 不关联
//                        $final_settlement = $settlement_order;
//                    }
                    if (false) {//$bizCommissionInfo['relevant_evaluation'] == 1
                        # 门店设置里面关联评价
                        $final_settlement = $settlement_order * $settlement_ratio;
                    } else {
                        # 门店设置  不 关联评价
                        $final_settlement = $settlement_order;
                    }
                } else {
                    # 自定义服务
                    $final_settlement = $settlement_order;
                }
                Db::table('order_server')->where(array('id' => $v['id']))->update(array('final_settlement' => $final_settlement));
                $price += $final_settlement;
            } else {
                # 商品工单
                # 计算抽成
                if ($v['custommark'] == 1) {
                    # 系统商品
//                    $withdrawal_amount = $v['price_settlement'] * $bizCommissionInfo['extract_platpro'];
                    $withdrawal_amount = $v['price_settlement'] * $drawRatio;
//                    $withdrawal_amount_count += $v['price_settlement'] * $bizCommissionInfo['extract_platpro'] * $settlement_ratio;
                    $withdrawal_amount_count += $v['price_settlement'] * $drawRatio * $settlement_ratio;
                } else {
                    # 自定义商品
//                    $withdrawal_amount = $v['price_settlement'] * $bizCommissionInfo['extract_selfpro'];
                    $withdrawal_amount = $v['price_settlement'] * $drawRatio;
//                    $withdrawal_amount_count += $v['price_settlement'] * $bizCommissionInfo['extract_selfpro'];
                    $withdrawal_amount_count += $v['price_settlement'] * $drawRatio;
                }
                $settlement_order = $v['price_settlement'] - $withdrawal_amount;
                # 结算金额
                if ($v['custommark'] == 1) {
                    # 系统商品,最终结算价格
                    $final_settlement = $settlement_order * $settlement_ratio;
                } else {
                    # 自定义商品
                    $final_settlement = $settlement_order;
                }
                Db::table('order_biz')->where(array('id' => $v['id']))->update(array('final_settlement' => $final_settlement));
                $price += $final_settlement;
            }
        }
        return array('price' => $price, 'commission_price' => $withdrawal_amount_count);
    }

    /**
     * @param $order_number
     * @return array
     * @throws \Yansongda\Pay\Exceptions\GatewayException
     * @throws \Yansongda\Pay\Exceptions\InvalidArgumentException
     * @throws \Yansongda\Pay\Exceptions\InvalidConfigException
     * @throws \Yansongda\Pay\Exceptions\InvalidSignException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @content 未到店退款
     */
    static function notInStore($order_number, $refundRatio = 0.5)
    {
        if (empty($order_number)) {
            return array('status' => false, 'msg' => '订单编号不能为空');
        }

        # 查询订单信息
        $orderInfo = Db::table('orders')->field('id,order_number,pay_price,member_id,order_type,order_status,pay_type,voucher_price,biz_id')->where(array('order_number' => $order_number))->find();
        if (empty($orderInfo)) {
            return array('status' => false, 'msg' => '订单信息为空');
        }
        if ($orderInfo['order_type'] != 3) {
            return array('status' => false, 'msg' => '该订单不是预约订单');
        }
        if ($orderInfo['order_status'] == 5) {
            return array('status' => false, 'msg' => '该订单已完成,无法取消');
        }
        if ($orderInfo['order_status'] > 3 and $orderInfo['order_status'] != 6) {
            return array('status' => false, 'msg' => '该订单已经处理过');
        }
        # 计算退款金额
        $refund_amount = floatval($orderInfo['pay_price']) * $refundRatio;
//        if ($refund_amount <= 0) {
//            $redis = new Redis();
//            $redis->hDel('payRedis' . $orderInfo['biz_id'], $order_number);
//            Db::table("orders")->where(array("id" => $orderInfo['id']))->update(array("order_status" => 4));
//            $res =  array('status' => true, 'msg' => '无需退款');
//        }
        # 退款---原路退回50%
        if ($orderInfo['pay_type'] == 1 && $refund_amount > 0) {
            # 微信退款
            $order = [
                'out_trade_no' => $order_number,
                'out_refund_no' => date('YmdHis') . time(),
                'total_fee' => $orderInfo['pay_price'] * 100,
                'refund_fee' => $refund_amount * 100,
                'refund_desc' => '订单退款',
            ];
            $payment = new Payment($order);
            $res = $payment->refund_wx();
//            $refund = new OrdersPay();
//            $res = $refund->wxRefund($order_number, $orderInfo['pay_price'], $refund_amount);
        } elseif ($orderInfo['pay_type'] == 2 && $refund_amount > 0) {
            # 支付宝退款
            /* $order = [
                 'out_trade_no' => $order_number,
                 'refund_amount' => $refund_amount,
             ];
             $payment = new Payment($order);
             $res = $payment->refund_ali();*/
            $refund = new OrdersPay();
            $res = $refund->aliRefund($order_number, $refund_amount);
        } elseif ($orderInfo['pay_type'] == 5 && $refund_amount > 0) {
            # 余额退款
            Db::table('member_mapping')->where(array('member_id' => $orderInfo['member_id']))->setInc('member_balance', $refund_amount);
            $redis = new Redis();
            $redis->hDel('payRedis' . $orderInfo['biz_id'], $order_number);
            $res = array('status' => true, 'msg' => '退款成功', 'refund_no' => date('YmdHis'));
        } else {
            $res = array('status' => true, 'msg' => '无法退款');
        }
        if ($res['status']) {
            $redis = new Redis();
            $redis->hDel('payRedis' . $orderInfo['biz_id'], $order_number);
            # 修改订单状态
            Db::table("orders")->where(array("id" => $orderInfo['id']))->update(array("order_status" => 4));
            # 判断卡券金额
            if ($orderInfo['voucher_price'] > 0) {
                Db::table("member_voucher")
                    ->where(array("order_id" => $orderInfo['id']))
                    ->update(array("status" => 1));
                # 删除卡券使用
                Db::table('log_cashcoupon')->where(array('order_number' => $order_number, 'member_id' => $orderInfo['member_id']))->delete();
            }
            //  # 删除这条消费记录
            // Db::table("log_consump")->where(array("order_number"=>$order_number))->delete();
            # 添加一条消费记录
            if ($refund_amount > 0) {
                Db::table("refund_log")->insert(array(
                    'order_number' => $order_number,
                    'refund_number' => $res['refund_no'],
                    "refund_time" => date("Y-m-d H:i:s", time()),
                    "member_id" => $orderInfo['member_id'],
                    "price" => $refund_amount,
                    "type" => $orderInfo['pay_type']
                ));
                $consump = Db::table("log_consump")->where(array("order_number" => $order_number))->find();
                if (!empty($consump)) {
                    unset($consump['id']);
                } else {
                    $consump['order_number'] = $order_number;
                    $consump['member_id'] = $orderInfo['member_id'];
                }
                $consump['consump_time'] = date("Y-m-d H:i:s");
                $consump['log_consump_type'] = 2;
                $consump['income_type'] = 15;
                $consump['consump_price'] = floatval($refund_amount);
                Db::table("log_consump")->insert($consump);
            }
        }
        return $res;
    }
}
